package com.lianzhihui.romeex.ui.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.config.AppStatusManager;
import com.lianzhihui.romeex.config.MessageEvent;
import com.lianzhihui.romeex.database.DataBaseManager;
import com.lianzhihui.romeex.inter.DialogListener;
import com.lianzhihui.romeex.ui.SplashActivity;
import com.lianzhihui.romeex.utils.MyToast;
import com.lianzhihui.romeex.utils.NetUtil;
import com.lianzhihui.romeex.utils.helper.LocaleManager;
import com.lianzhihui.romeex.widget.LoadingDialog;
import com.lianzhihui.romeex.widget.dialog.PasswordDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AppCompatActivity {
    protected String TAG = this.getClass().getSimpleName();
    protected BaseActivity mActivity;
    protected RxPermissions rxPermissions;
    protected int pageNum = 1;
    protected int pageNum2 = 1;
    //这里用来判断重复频繁点击问题
    protected boolean clickable = true;
    protected View barView;
    //toolbar（如果存在）设置方法
    protected TextView titleTv, optionTv;
    ImageView backIv;
    private LoadingDialog loadingDialog;

    private View contentViewGroup;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //判断app状态
        if (AppStatusManager.getInstance().getAppStatus() == AppConstants.AppStatus.STATUS_RECYCLE) {
            //被回收，跳转到启动页面
            Intent intent = new Intent(this, SplashActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        ActivityManager.getInstance().pushOneActivity(this);
        EventBus.getDefault().register(this);
        //竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //避免5.0修改不到顶部颜色导致看不到顶部的状态

        //状态栏中的文字颜色和图标颜色，需要android系统6.0以上，而且目前只有一种可以修改（一种是深色，一种是浅色即白色）
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//        }
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(getResources().getColor(R.color.window_bg));
        setContentView(this.getLayoutId());
        setFitSystemWindow();
        ButterKnife.bind(this);
        mActivity = this;
        rxPermissions = new RxPermissions(this);
        initBar();
        initView();
        initData();
    }

    /**
     * 白色状态栏
     */
    protected void whiteStauebar() {
        getWindow().setStatusBarColor(getResources().getColor(R.color.white));
    }

    /**
     * 自定义状态栏
     */
    protected void custStauebar(int color) {
        getWindow().setStatusBarColor(getResources().getColor(color));
    }

    protected void setFitSystemWindow() {
        if (setFitSystemWindowFlag()) {
            if (contentViewGroup == null) {
                contentViewGroup = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
            }
            contentViewGroup.setFitsSystemWindows(true);
        }

    }


    public void showFullScreen() {
        Window window = getWindow();
        View decorView = window.getDecorView();
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(option);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    //定义视图抽象方法
    protected abstract int getLayoutId();

    //定义初始化抽象方法
    protected abstract void initView();

    //设置数据的抽象方法
    protected abstract void initData();

    //是否全屏
    public boolean setFitSystemWindowFlag() {
        return true;
    }


    @NotNull
    public String getStringValues(int resId) {
        return getResources().getString(resId);
    }

    //默认不开启软键盘
    private void onInputDef() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    /**
     * @ProjectName: NBN
     * @ClassName: BaseActivity
     * @Description: 设置下划线
     * @Author: 赵峰（zhaofengcto@foxmail.com）
     * @CreateDate: 2020/10/29 11:47
     * @UpdateUser: 更新者
     * @UpdateDate: 2020/10/29 11:47
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    public void setTextUnderLine(TextView targetView) {
        targetView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        targetView.getPaint().setAntiAlias(true);//抗锯齿
    }

    @NotNull
    public int getColorValues(int resId) {
        return ContextCompat.getColor(this, resId);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleManager.setLocale(base));
    }


    public void copyString(String string) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setText(string);
        Toast.makeText(mActivity, getResources().getString(R.string.toast_copy_success), Toast.LENGTH_SHORT).show();
    }

    /**
     * 是否有网络
     *
     * @return
     */
    public boolean hasNet() {
        int state = NetUtil.getNetWorkState(this);
        if (state == NetUtil.NETWORK_NONE) {
            MyToast.showToast(getResources().getString(R.string.toast_no_net));
            return false;
        } else {
            return true;
        }
    }

    /**
     * @ProjectName: NBN
     * @ClassName: BaseActivity
     * @Description: 申请权限
     * @Author: 赵峰（zhaofengcto@foxmail.com）
     * @CreateDate: 2020/10/29 11:50
     * @UpdateUser: 更新者
     * @UpdateDate: 2020/10/29 11:50
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @SuppressLint("CheckResult")
    public void checkPermission() {
        rxPermissions.request(Manifest.permission.CAMERA
                , Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
//                , Manifest.permission.ACCESS_NOTIFICATION_POLICY
        )
                .subscribe(granted -> {
                    if (granted) {
                        // Always true pre-M
                        // I can control the camera now
                    } else {
                        // Oups permission denied
                        MyToast.showToast("请授予权限以保证程序正常运行");
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        ActivityManager.getInstance().popOneActivity(this);
//        if (loadingDialog != null && loadingDialog.isShowing()) {
//            dismissLoading();
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        hasNet();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    /**
     * 使用SP 的尺寸不受 系统字体的影响而改变，防止出现字体放大而出现的布局问题
     *
     * @return
     */
    @Override
    public Resources getResources() {//还原字体大小
        Resources res = super.getResources();
        //非默认值
        if (res.getConfiguration().fontScale != 1) {
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    /**
     * 初始化bar
     */
    private void initBar() {

        barView = findViewById(R.id.app_top_bar);
        if (barView != null) {
            backIv = barView.findViewById(R.id.include_top_iv_back);
            backIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            titleTv = barView.findViewById(R.id.include_top_tv_title);
            optionTv = barView.findViewById(R.id.include_top_tv_right);
        }

    }

    protected void hideBar() {
        if (barView != null) {
            barView.setVisibility(View.GONE);
        }
    }

    protected void showBar() {
        if (barView != null) {
            barView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置title
     *
     * @param title
     */
    protected void setTitle(String title) {
        if (titleTv != null && title != null) {
            titleTv.setText(title);
        }

    }


    /**
     * 隐藏返回键
     */
    protected void hideBack() {
        if (backIv != null) {
            backIv.setVisibility(View.INVISIBLE);
        }
    }

    protected void showLoading(){
        showLoading("");
    }

    protected void showLoading(String title) {
        if (this.isDestroyed()) {
            return;
        }
        try {
            if (loadingDialog == null) {
                loadingDialog = new LoadingDialog(this);
                loadingDialog.setTitle(title);
                loadingDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        clickable = true;
                    }
                });
                loadingDialog.center();
                loadingDialog.setWidthWrap();
                loadingDialog.show();
            } else {
                loadingDialog.setTitle(title);
                loadingDialog.show();
            }
        } catch (Exception e) {

        }
    }

    protected void dismissLoading() {
        if (this.isDestroyed()) {
            return;
        }
        try {
            if (loadingDialog != null) {
                if (loadingDialog.isShowing()) { //check if dialog is showing.
                    //get the Context object that was used to great the dialog
                    Context context = ((ContextWrapper) loadingDialog.getContext()).getBaseContext();
                    //if the Context used here was an activity AND it hasn't been finished or destroyed
                    //then dismiss it
                    if (context instanceof Activity) {
                        if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed())
                            loadingDialog.dismiss();
                    } else //if the Context used wasnt an Activity, then dismiss it too
                        loadingDialog.dismiss();
                }
                loadingDialog = null;
            }
        } catch (Exception e) {

        }

    }

    /**
     * 权限申请
     */
    @SuppressLint("CheckResult")
    protected void checkPermissions(String permission) {
        rxPermissions.request(permission)
                .subscribe(granted -> {
                    if (granted) {
                        onPermission(permission, true);
                    } else {
                        onPermission(permission, false);
                    }
                });

    }

    protected void onPermission(String permisstion, boolean isGranted) {

    }

    public void ocStartActivity(Intent intent) {
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        super.startActivity(intent);

    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(0, 0);
    }

    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    public void showInput(final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 空记录 布局
     *
     * @return
     */
    public View getEmptyView() {
        View emptyView = getLayoutInflater().inflate(R.layout.layout_empty_view, null);
        emptyView.findViewById(R.id.emptyRoot).setVisibility(View.VISIBLE);
        return emptyView;
    }

    /**
     * 自定义空布局
     *
     * @param id 图片资源
     * @param at 显示文字
     * @return
     */
    public View getEmptyView(int id, String at) {
        View emptyView = getLayoutInflater().inflate(R.layout.layout_empty_view, null);
        ImageView iv_icon = emptyView.findViewById(R.id.iv_icon);
        iv_icon.setImageResource(id);
        TextView tv_content = emptyView.findViewById(R.id.tv_content);
        tv_content.setText(at);
        emptyView.findViewById(R.id.emptyRoot).setVisibility(View.VISIBLE);
        return emptyView;
    }

    // 成员变量mToast
    private Toast mToast;

    /**
     * 设置title
     *
     * @param title
     */
    protected void setOption(String title, View.OnClickListener listener) {
        if (optionTv != null && title != null) {
            optionTv.setText(title);
            optionTv.setTextColor(getResources().getColor(R.color.black));
            optionTv.setOnClickListener(listener);
        }
    }

    protected void showSafty(DialogListener listener){
        PasswordDialog dialog = new PasswordDialog(this, getString(R.string.input_password));
        dialog.setListener(listener);
        dialog.show();
    }

    /**
     * 显示 toast,在可是界面中优先使用该方法
     *
     * @param content
     */
    protected void toast(String content) {
        // 显示Toast
        if (mToast == null) {
            mToast = Toast.makeText(this, content, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(content);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    /**
     * eventbus 发送消息
     * @param event
     * @param obj
     */
    protected void sendMessage(int event,Object obj){
        EventBus.getDefault().post(new MessageEvent(event,obj));
    }

}
